package com.atguigu.ssyx.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.ssyx.common.auth.AuthContextHolder;
import com.atguigu.ssyx.common.constant.RedisConst;
import com.atguigu.ssyx.common.exception.SsyxException;
import com.atguigu.ssyx.common.result.Result;
import com.atguigu.ssyx.common.result.ResultCodeEnum;
import com.atguigu.ssyx.common.utils.JwtHelper;
import com.atguigu.ssyx.enums.UserType;
import com.atguigu.ssyx.model.user.User;
import com.atguigu.ssyx.user.service.UserService;
import com.atguigu.ssyx.user.utils.ConstantPropertiesUtil;
import com.atguigu.ssyx.user.utils.HttpClientUtils;
import com.atguigu.ssyx.vo.user.LeaderAddressVo;
import com.atguigu.ssyx.vo.user.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "微信登录接口")
@RestController
@RequestMapping("/api/user/weixin")
public class WechatApiController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /*
     * 微信授权登录
     */
    @ApiOperation("微信授权登录获取openId(小程序)")
    @GetMapping("/wxLogin/{code}")
    public Result wxLogin(@PathVariable String code) {
        // 获取微信返回的code值，即临时票据
        // 通过code值 + 小程序id + 小程序密钥，调用微信接口服务
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String wxOpenAppId = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        String wxOpenAppSecret = ConstantPropertiesUtil.WX_OPEN_APP_SECRET;
        // 拼接url
        StringBuffer sb = new StringBuffer();
        sb.append(url)
                .append("?appid=").append(wxOpenAppId)
                .append("&secret=").append(wxOpenAppSecret)
                .append("&js_code=").append(code)
                .append("&grant_type=authorization_code");
        String wxResult = String.format(sb.toString(), wxOpenAppId, wxOpenAppSecret, code);
        /// 使用HttpClient工具类,发送get请求，获取返回数据
        String result = null;
        try {
            result = HttpClientUtils.get(wxResult);
        } catch (Exception e) {
            throw new SsyxException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }
        // 获取返回数据，获取openid(微信唯一标识)和session_key
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openId = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
        // 保存微信用户信息到数据库中
        /// 根据openId，判断是否是第一次授权登录
        User user = userService.getUserByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user.setNickName(openId);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0);
            userService.save(user);
        }
        // 根据userId查询提货点和团长信息
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());
        // 使用JWT工具根据userId和userName生成token
        String token = JwtHelper.createToken(user.getId(), user.getNickName());
        // 获取当前用户的登录信息，放入redis中，设置有效时间
        UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId());
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(),
                userLoginVo, RedisConst.USERKEY_TIMEOUT, TimeUnit.DAYS);
        // 封装数据到map集合中
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        map.put("leaderAddressVo", leaderAddressVo);
        return Result.ok(map);
    }

    /*
     * 更新用户昵称与头像
     */
    @PostMapping("/auth/updateUser")
    @ApiOperation(value = "更新用户昵称与头像")
    public Result updateUser(@RequestBody User user) {
        //获取当前登录用户id
        User user1 = userService.getById(AuthContextHolder.getUserId());
        //把昵称更新为微信用户
        user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
        user1.setPhotoUrl(user.getPhotoUrl());
        userService.updateById(user1);
        return Result.ok(null);
    }
}
